Indexes

Indexes in SQL programming are nothing but a special data structure used to easily and quickly locate the record in a given table of the database without being required to traverse through each and every record of the table. Indexes are easily generated using one or more columns of a given table. As a note, the data structure used by an index is a Binary Tree (B-Tree). In MongoDB, indexes plays a vital role in efficiently execution of the queries. Basically, if no index is defined in MongoDB, then it has to scan every document of a given collection. Hence, MongoDB uses index to reduce the number of documents to be scanned in a given collection. In fact, MongoDB's index is more or less similar to the indexes used in other relational databases. The fact is that the MongoDB defines the indexes at the collection level and supports indexing on any fields in a MongoDB collection.

Default Index in MongoDB
Mongodb provides a default index named _id which acts as a primary key to access any document in a collection. This _id index basically avoids the insertion of 2 documents with the same value for the _id field.

Creating an Index using createIndex()
To create an index in MongoDB, run the following command :
db.collection_name.createIndex({field : value })
To create an index on the field regNo for a student collection, run the command db.student.createIndex({regNo : 1})

We can also create Index on multiple fields by running a single command. The command will be : db.student.createIndex({regNo : 1, address : -1})  

Finding Indexes in collection
db.collection_name.getIndexex()


Drop Indexes
db.collection_name.dropIndexex({index_name: 1})

Droping all the indexes:
db.collection_name.dropIndexex()

No comments:

Post a Comment